package com.whq.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.whq.utils.AccessTokenUtils;
import com.whq.utils.HttpClientUtils;
import com.whq.utils.JedisUtils;
import com.whq.utils.StringUtils;
import com.whq.websocket.SystemWebSocketHandler;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.socket.TextMessage;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Map;

/**
 * Created by qpx on 2017/12/9.
 */
@Controller
public class BackstageLoginController {


    public static String QRCODE_CREATE_URL  = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={token}";
    public static String SHOW_QRCODE_URL = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={ticket}";
    private static Logger logger = LoggerFactory.getLogger(BackstageLoginController.class);
    @RequestMapping("/toBackstageLogin/{id}/{name}/{age}")
    public String toLogin(ModelMap model, @CookieValue(value = "name") @ModelAttribute  String name, @PathVariable(value = "id") int ids, @PathVariable String names, @PathVariable int ages) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
        String ticket = JedisUtils.get("ticket");
        if(StringUtils.isNotEmpty(ticket)){
            SHOW_QRCODE_URL = SHOW_QRCODE_URL.replace("{ticket}",ticket);
            model.put("url",SHOW_QRCODE_URL);
            return "loginBackstage";
        }
        //调用微信获取token
        String token = AccessTokenUtils.getAccessToken();
        //{"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "test"}}}
        Map<String,Object> map = Maps.newHashMap();
        map.put("action_name","QR_LIMIT_STR_SCENE");
        Map<String,Object> scenestr = Maps.newHashMap();
        scenestr.put("scene_str","toBackstageLogin");
        Map<String,Object> scene = Maps.newHashMap();
        scene.put("scene",scenestr);
        map.put("action_info",scene);
        String json =JSON.toJSONString(map);
        logger.info(JSON.toJSONString(map));
        QRCODE_CREATE_URL = QRCODE_CREATE_URL.replace("{token}",token);
        JSONObject post = HttpClientUtils.sendSSL(QRCODE_CREATE_URL, "POST", json);
        ticket = post.get("ticket").toString();
        if(StringUtils.isNotEmpty(ticket)){
            JedisUtils.set("ticket",ticket,0);
            SHOW_QRCODE_URL = SHOW_QRCODE_URL.replace("{ticket}",ticket);
            model.put("url",SHOW_QRCODE_URL);
        }
        logger.info(JSON.toJSONString(post));
        return "loginBackstage";
    }

    @RequestMapping("/test")
    @ResponseBody
    public String test(){
        SystemWebSocketHandler systemWebSocketHandler = new SystemWebSocketHandler();
        systemWebSocketHandler.sendMessageToUser("123456",new TextMessage("12345"));
        return "ok";
    }

    public static void main(String[] args) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
        //调用微信
        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={token}";
        String token = AccessTokenUtils.getAccessToken();
        //{"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "test"}}}
        Map<String,Object> map = Maps.newHashMap();
        map.put("action_name","QR_LIMIT_STR_SCENE");
        Map<String,Object> scenestr = Maps.newHashMap();
//        scene.put("scene_id","100000");
        scenestr.put("scene_str","toBackstageLogin");
        Map<String,Object> scene = Maps.newHashMap();
        scene.put("scene",scenestr);
        map.put("action_info",scene);
        String json =JSON.toJSONString(map);
        logger.info(JSON.toJSONString(map));
        url = url.replace("{token}",token);
        Integer a = 200;
        a.intValue();
        JSONObject post = HttpClientUtils.sendSSL(url, "POST", json);
        logger.info(JSON.toJSONString(post));
    }

}
